package com.young.dao_.dao;

import com.young.dao_.domian.Student;
import com.young.dao_.utils.JdbcUtilsByDruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author: young
 * @Date: 2021-12-04 8:59
 * @Description: 开发BasicDAO，是其他DAO的父类
 */
// 泛型指定具体类型
public class BasicDAO<T> {
	private QueryRunner qr = new QueryRunner();
	
	// 开发通用的dml方法，针对任意表
	public int update(String sql,Object... params){
		Connection connection = null;
		try {
			connection = JdbcUtilsByDruid.getConnection();
			
			int update = qr.update(connection, sql, params);
			return update;
		} catch (SQLException e) {
			throw new RuntimeException(e);  //将编译异常 -> 运行异常，抛出
		}finally {
			JdbcUtilsByDruid.close(null,null,connection);
		}
	}
	
	// 返回多个对象（即查询结果是多行的），针对任意表
	public List<T> queryMany(String sql, Class<T> clazz, int params){
		Connection connection = null;
		
		try {
			connection = JdbcUtilsByDruid.getConnection();
			
			return qr.query(connection, sql, new BeanListHandler<>(clazz), params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			JdbcUtilsByDruid.close(null,null,connection);
		}
	}
	
	// 返回单行的结果
	public T querySingle(String sql, Class<T> clazz, Object... params){
		Connection connection = null;
		
		try {
			connection = JdbcUtilsByDruid.getConnection();
			
			return qr.query(connection, sql,new BeanHandler<T>(clazz), params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			JdbcUtilsByDruid.close(null,null,connection);
		}
	}
	
	//  返回单行单列结果
	public Object queryScalar(String sql, Object... params){
		Connection connection = null;
		
		try {
			connection = JdbcUtilsByDruid.getConnection();
			
			return qr.query(connection, sql, new ScalarHandler<>(), params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			JdbcUtilsByDruid.close(null,null,connection);
		}
	}
}
